# -*- coding: utf-8 -*-
import requests

from lxml.html import document_fromstring as HTML_Parser

class HNParser():
	def __init__(self):
		self.MainURL = "https://news.ycombinator.com/"

	def make_border(self, lines):
		max_len = len(max(lines, key = len, default = ''))
		return '=' * (max_len + 5) + '\n' + '\n'.join('# {:<{width}} #'.format(l, width = max_len + 1) for l in lines) + '\n' + '=' * (max_len + 5)

	def GetNews(self):
		NextURL = "newest"

		while True:
			NewsItemsResponse = requests.get(self.MainURL + NextURL, headers = {"User-Agent": "Mozilla/5.0 (Linux; arm; Android 7.1.1; Moto E (4) Plus) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 YaBrowser/21.2.6.68.00 SA/3 TA/7.1 Mobile Safari/537.36"})

			if NewsItemsResponse.status_code != 200:
				print("\nError: Response Code is {0}".format(NewsItemsResponse.status_code))
				break

			NewsItemsHTML = HTML_Parser(NewsItemsResponse.text)

			NewsItems = NewsItemsHTML.xpath("//a[@class=\"storylink\"]")

			for NewsItem in NewsItems:
				GitHubURL = NewsItem.xpath("@href")[0]

				if "github.com" in GitHubURL:
					lines = "Title: {0}".format(NewsItem.text), "GitHub: {0}".format(GitHubURL)
					print(self.make_border(lines))

			try:
				NextURL = NewsItemsHTML.xpath("//a[@class=\"morelink\"]/@href")[0]
			except:
				print("\nError: Not Found MoreLink")
				break

if __name__ == '__main__':
	HN = HNParser()
	HN.GetNews()